package baidu;

import java.io.*;
import java.util.HashMap;

import org.json.JSONObject;

import com.baidu.aip.speech.AipSpeech;
import com.baidu.aip.speech.TtsResponse;
import com.baidu.aip.util.Util;

import javazoom.jl.player.Player;

public class SpeechBaidu {
    //设置APPID/AK/SK
    public static final String APP_ID = "15749596";
    public static final String API_KEY = "vD3O5V7UeSGnTeEouTbHw1sC";
    public static final String SECRET_KEY = "4mEuWrVEuIU1Cu07oeaF0tchr0NPMy7E";

    //配置信息
    public static AipSpeech client = new AipSpeech(APP_ID, API_KEY, SECRET_KEY);

    //说话
    public static void speak(final String content) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                //调用接口
                //设置可选参数
                HashMap<String, Object> options = new HashMap<String, Object>();
                options.put("spd", "6");
                options.put("pit", "5");
                options.put("per", "4");
                TtsResponse res = client.synthesis(content, "zh", 1, options);
                byte[] data = res.getData();
                JSONObject res1 = res.getResult();

                //音频播放
                if (data != null) {
                    try {
                        String fileName = "speak" + System.currentTimeMillis() + ".mp3";
                        Util.writeBytesToFileSystem(data, fileName);
                        playVoice(fileName);
                        new File(fileName).delete();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }

    //播放
    public static void playVoice(String fileName) {
        Player player;
        BufferedInputStream buffer;
        try {
            buffer = new BufferedInputStream(new FileInputStream(fileName));
            player = new Player(buffer);
            player.play();
            if (buffer != null) {
                buffer.close();
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

